import '@/js_sdk/AppLog/AppLog.js' // 引入日志插件工具

// 设备组网发现服务
export const useDeviceDiscoverStore = defineStore('deviceDiscover', () => {
  // 声明插件
  const udpLib = uni.requireNativePlugin?.('udp-tool')
  const netTool = uni.requireNativePlugin?.('net-tool')

  // udp服务运行状态
  let udpServerRunning = ref(false)

  // udp服务监听端口
  let udpServerPort = 30313

  // tcp服务监听本机IP
  let tcpServerIp = ''

  // tcp服务监听端口
  let tcpServerPort = 31313

  // 设备会话列表
  let deviceSessionList = reactive([])

  // 设备广播消息处理回调
  let deviceBoardcastCallbackObj = null
  function registerDeviceBoardcastCallback(callback, context = null) {
    if (typeof callback !== 'function') {
      throw new Error('callback must be a function')
    }
    g_utils.writeLog('注册UDP广播事件回调')
    let callbackFunc = callback
    deviceBoardcastCallbackObj = {
      callbackFunc,
      context
    }
  }
  function unregisterDeviceBoardcastCallback() {
    deviceBoardcastCallbackObj = null
  }

  // 启动UDP服务
  function startUdpServer() {
    if (udpServerRunning.value) {
      return
    }
    g_utils.writeLog('start UDP Server')
    udpServerRunning.value = true
    Object.assign(deviceSessionList, []) // 清空数组

    udpLib.init(
      udpServerPort,
      true,
      resData => {
        // resData 的数据结构：{host: string, port: number, data: string, hex: string}
        g_utils.writeLog('UDP接收到消息:', resData)
        let msgText = resData.data
        // 样例：1,neoway,1,5ENDU193060,20313
        const [messageType, deviceBrand, deviceCategory, deviceSN, devicePort] =
          msgText.split(',')
        if (
          deviceSN === undefined ||
          deviceSN === null ||
          deviceSN.trim() === ''
        ) {
          g_utils.writeLog('device sn is empty')
          return
        }
        if (parseInt(messageType, 10) != 1) {
          g_utils.writeLog('not support message type')
          return
        }
        // 会话
        let deviceSession = {
          sn: deviceSN,
          brand: deviceBrand,
          category: parseInt(deviceCategory), // 1：炒菜机；2：油烟机；3：电子秤
          ip: resData.host,
          port: parseInt(devicePort, 10),
          createDate: new Date()
        }

        const index = deviceSessionList.findIndex(item => item.sn === deviceSN)
        if (index !== -1) {
          g_utils.writeLog('刷新设备会话：', deviceSession)
          deviceSessionList.splice(index, 1, deviceSession) // 替换元素
        } else {
          g_utils.writeLog('新增设备会话：', deviceSession)
          deviceSessionList.push(deviceSession)
        }

        // 校验设备是否合法。只有合法的设备才回复链接地址消息
        // 通过SN号校验是否合法即可
        if (deviceBoardcastCallbackObj != null) {
          let { callbackFunc, context } = deviceBoardcastCallbackObj
          let result = callbackFunc.call(context, deviceSession)
          g_utils.writeLog('UDP广播回调结果：', result)
          if (result) {
            // 响应合法设备消息
            udpLib.send({
              host: deviceSession.ip,
              port: deviceSession.port,
              data: `1,${tcpServerPort}`
            })
          }
        }

        // if (tcpServerIp != "") {
        //     udpLib.send({
        //         host: deviceSession.ip,
        //         port: deviceSession.port,
        //         data: `2,${tcpServerPort}`,
        //         useHex: false,
        //     })
        // } else {
        //     netTool.getLocalIpAddress((result)=>{
        //         if (result == "") {
        //             g_utils.writeLog("暂时无法获取有效的IP地址：", result)
        //             return
        //         }
        //         tcpServerIp = result
        //         udpLib.send({
        //             host: deviceSession.ip,
        //             port: deviceSession.port,
        //             data: `2,${tcpServerIp},${tcpServerPort}`,
        //             useHex: false,
        //         })
        //     })
        // }
      },
      errMsg => {
        console.error('udp socket 异常:' + errMsg)
      }
    )
  }

  // 停止UDP服务
  function stopUdpServer() {
    g_utils.writeLog('stop UDP Server')
    if (udpServerRunning.value) {
      udpServerRunning.value = false
      udpLib.release()
    }
  }

  // UDP服务是否运行中
  function isUdpServerRunning() {
    return udpServerRunning
  }
  function isUdpAlive() {
      return udpLib.isAlive()
  }

  // 获取设备会话
  function getDeviceSessionList() {
    return deviceSessionList
  }

  // 返回API
  return {
    registerDeviceBoardcastCallback,
    unregisterDeviceBoardcastCallback,
    getDeviceSessionList,
    isUdpServerRunning,
    startUdpServer,
    stopUdpServer,
    isUdpAlive
  }
})

export function useOutsideDeviceDiscoverStore() {
  return useDeviceDiscoverStore(g_store)
}
